#ifdef FORW_POINT_SUPPORT
#ifndef FSUPPORT_CPP 
#define FSUPPORT_CPP 1

#include "csp_base.h"
#include "bsupport.h"
#include <iostream>

using namespace std;


ForwSupportList::~ForwSupportList()
{
	//cout << "Destructor: ForwSupportList Begin" << endl;
	if(nlist!=NULL) delete [] nlist;
	//cout << "Destructor: ForwSupportList End" << endl;
}

void ForwSupportList::deleteNode(ForwSupportNode* node)
{
	//cout << "Deleting node: " << (void*)node << endl;
	node->next=nextEmpty->next;
	if(nextEmpty->next!=NULL)
		nextEmpty->next->pre=node;
	nextEmpty->next=node;
	node->pre=nextEmpty;
	//cout << " Done." << endl;

	//count--;
	//cout << "removeSupport removed:" << count<< endl;
}

void ForwSupportList::generateList(int numvar, int domsize,int edges)
{
	//cout << "Generating list" << endl;
	listcount=edges*domsize*2+1;
	nlist= new ForwSupportNode[listcount];
	//if(lists==NULL)
	//{
		//cout << "Failure! Not enough memory for support list!" << endl;
	//	exit(1);
	//}
	nextEmpty=nlist;
	
	ForwSupportNode* sp=nlist;
	sp->pre=NULL;
	for(int i=0;i<listcount-1;i++)
	{
		sp->value=0;
		sp->varia=0;
		sp->next=sp+1;
		sp++;
		sp->pre=sp-1;
	}
	sp->value=0;
	sp->varia=0;
	sp->next=NULL;

	//cout << "Generated super support list" << endl;
}
//Val2 in Var2 has support from Val in Var
ForwSupportNode* ForwSupportList::setSupport(Domain* var,int val,int var2,int val2) 
{
	ForwSupportNode* retval=nextEmpty;
	nextEmpty=retval->next;
	retval->varia=var2;
	retval->value=val2;
	retval->pre=NULL;
	if(var[val].supported==NULL)
		retval->next=NULL;
	else
	{
		var[val].supported->pre=retval;
		retval->next=var[val].supported;
	}
	var[val].supported=retval;
	return retval;
}

//move support for *node from val1 to val2 in var
void ForwSupportList::moveSupport(Domain* var,int val1,int val2,ForwSupportNode* node)
{
	if(node->pre!=NULL)
	{
		//cout << "Previous supports... ";
		ForwSupportNode* prev=node->pre;
		prev->next=node->next;
		if(node->next!=NULL)
		{
			//cout << "Next supports... Done" << endl;
			node->next->pre=prev;
		}
		else
		{
			//cout << "No next supports. Done" << endl;
		}
	}
	else if(node->next!=NULL)
	{
		//cout << "Next Supports... Done" << endl;
		var[val].supported=node->next;
		var[val].supported->pre=NULL;
	}
	else
	{
		//cout << "Only Dependant, removing node" << endl;
		var[val].supported=NULL;
	}
	//node removed from previous value, attaching to new value

	node->pre=NULL;
	if(var[val2].supported==NULL)
		node->next=NULL;
	else
	{
		var[val2].supported->pre=node;
		node->next=var[val2].supported;
	}
	var[val2].supported=node;

}
#endif
#endif
